﻿using System;
using System.Linq;
using System.Data;
using org.se.fs.presenter.ITask.Profile;
using org.se.fs.presenter.IView.Template;
using org.se.fs.presenter.Library;

namespace org.se.fs.presenter.View.Profile
{
    public class ClientLists : Template.ViewLists
    {
        private readonly IFormLists _view;
        private readonly IClient _task;

        public ClientLists(IFormLists view) : this(view, new Task.Context.Client()) { }

        public ClientLists(IFormLists view, IClient task)
        {
            _view = view;
            _task = task;
        }

        protected override void TaskOnFetchLists(object source, FormEvent e)
        {
            if (!e.IsSuccess)
            {
                _view.Lists = null;
                _view.StatusLists = "Result: 0 records";
                return;
            }

            Lists = (DataTable)e.Value;
            DisplayData();
        }

        public override void Initialize()
        {
            Lists = new DataTable();
            _task.OnFetchLists += TaskOnFetchLists;
            _task.OnDelete += TaskOnDelete;
            _task.FetchLists(null);
        }

        protected override void TaskOnDelete(object source, FormEvent e)
        {
            TriggerDelete(new FormEvent(true) { Exception = e.Exception });

            if (!e.IsSuccess)
                return;

            var data = (DataTable)e.Value;
            foreach (var dr in Lists.Select().Where(dr => dr["id"].ToString().Equals(data.Rows[0]["id"].ToString())))
            {
                Lists.Rows.Remove(dr);
                break;
            }
            DisplayData();
        }

        public override void DisplayData()
        {
            _view.StatusLists = string.Format("Result: {0} records", Lists.Rows.Count);

            if (Lists.Rows.Count.Equals(0))
                _view.Lists = new DataTable();

            var a = (Lists.AsEnumerable().OrderBy(b => b.Field<string>("middle_name")).OrderBy(b => b.Field<string>("first_name")).OrderBy(b => b.Field<string>("last_name")));
            Lists = a.CopyToDataTable();
            var d = (Lists.AsEnumerable().Select(c => new
            {
                Name = string.Format("{0}, {1} {2}.", c.Field<string>("last_name"), c.Field<string>("first_name"), c.Field<string>("middle_name").Substring(0, 1)),
                Gender = c.Field<string>("gender"),
                Address = c.Field<string>("address"),
                Age = Math.Floor(DateTime.Now.Subtract(c.Field<DateTime>("birth_date")).TotalDays / 365),
                UserName = c.Field<string>("user_name")
            })).ToArray();
            _view.Lists = d;
        }

        public override void Remove(DataTable data)
        {
            if (data == null || Lists.Rows.Count.Equals(0) || data.Rows.Count.Equals(0))
                return;

            _task.Delete(data);
        }
    }
}
